package com.peng.leetcode.tree;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/**
 * PathSum2
 * 113. 路径总和 II
 * https://leetcode.cn/problems/path-sum-ii/
 * <p>
 * Created on 2022/11/27
 *
 * @author lupeng
 */
public class PathSum2 {

    List<List<Integer>> ans = new ArrayList<>();

    ArrayDeque<Integer> q = new ArrayDeque<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        this.dfs(root, targetSum);
        return ans;
    }

    private void dfs(TreeNode root, int targetSum) {
        if (root == null) {
            return;
        }
        q.offer(root.val);
        targetSum -= root.val;
        if (root.left == null && root.right == null && targetSum == 0) {
            ans.add(new ArrayList<>(q));
        }
        if (root.left != null) {
            dfs(root.left, targetSum);
        }
        if (root.right != null) {
            dfs(root.right, targetSum);
        }
        q.pollLast();
    }
}
